﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using iTextSharp.text;

namespace PocoReport
{
    public class List : IPart, IContainerPart
    {
        public Style Style { get; protected set; }
        public IList<IPart> Parts { get; protected set; }
        public string DataSource { get; set; }
        public string Value { get; set; }
        
        public List()
        {
            Style = new Style();
            Parts = new List<IPart>();
        }

        public void Load(XNode node)
        {
            XElement element = (XElement)node;
            Style = new Style(element);
            DataSource = element.GetAttribValue("DataSource", null);
            Value = element.GetAttribValue("Value", null);

            foreach (XElement partEement in element.Elements())
            {
                IPart part = PartFactory.GetPart(partEement);
                if(part != null)
                {
                    Parts.Add(part);
                }
            }
        }

        public XNode Save()
        {
            XElement element = new XElement("List");
            element.SetAttribValue("Style", Style);
            element.SetAttribValue("DataSource", DataSource);
            element.SetAttribValue("Value", Value);
            foreach (IPart part in Parts)
            {
                element.Add(part.Save());
            }
            return element;
        }

        public IElement GetPdfElement(Document document, Style parentStyle, Scope scope)
        {
            Style mergedStyle = Style.Merge(parentStyle, Style);
            iTextSharp.text.Paragraph list = iTextSharp.text.factories.ElementFactory.GetParagraph(mergedStyle.Properties);
            if(DataSource != null && Value != null)
            {
                IEnumerable dataSourceValue = (IEnumerable) scope.GetValue(DataSource);
                if (dataSourceValue != null)
                {
                    Scope innerScope = new Scope(scope);
                    foreach (object value in dataSourceValue)
                    {
                        innerScope.Set(Value, value);
                        foreach (IPart part in Parts)
                        {
                            IElement element = part.GetPdfElement(document, mergedStyle, innerScope);
                            list.Add(element);
                        }
                    }
                }
            }
            return list;
        }
    }
}
